/**
 * Created by yangxianming on 2017/9/11.
 */



//打开页面后 需要加载一些数据
function initializeData(){
    //请求第一次加载api列表的数据，默认全部列出来
    requestGetApiList("", "", "", "");
    //加载“所有项目”下拉菜单
    loadSelectList(document.getElementById("project"), projectList);
    //加载“请求方式”下拉菜单
    loadSelectList(document.getElementById("method"), methodList);
    //加载版本列表
    var xmlhttp2 = new XMLHttpRequest();
    xmlhttp2.onreadystatechange = function(){
        if (xmlhttp2.readyState==4){
            if (xmlhttp2.status==200){
                var r = JSON.parse(xmlhttp2.response);
                if (r["apiStatus"] == "1"){
                    var versionList = JSON.parse(xmlhttp2.response)['result']['datas'];
                    versionList.unshift("全部版本");
                    loadSelectList(document.getElementById("version"), versionList);
                }else{
                    alert(r["errorMsg"]);
                }
            }
        }
    };
    xmlhttp2.open("GET", "/apiTest/getVersionList", true);
    xmlhttp2.send();

}


//点击“添加”“编辑接口”，悬浮层页面设置
function controlTopDiv(mySwitch, text, trObject){
    var topDiv = document.getElementById('add&edit');
    if (mySwitch == "open") {
        //设置页面抬头
        document.getElementById('topDivTitle').innerText = text;
        //加载“所有项目”下拉菜单
        loadSelectList(document.getElementById("topDivProject"), projectList);
        document.getElementById("topDivProject").options.remove(0);
        //加载“请求方式”下拉菜单
        loadSelectList(document.getElementById("topDivMethod"), methodList);
        document.getElementById("topDivMethod").options.remove(0);

        if (trObject != undefined){
            document.getElementById("apiId").innerText = trObject.getAttribute("id");

            var td = trObject.getElementsByTagName("td");

            var topDivParameter = td[2].getAttribute("title").replace(/,/g, ",\n");
            topDivParameter = topDivParameter.replace(/&/g, "&\n");

            // -1 是因为编辑弹出框的下拉是过滤掉了“全部”选项
            document.getElementById("topDivMethod").options[methodList.indexOf(td[0].getAttribute("title"))-1].selected = true;
            document.getElementById("topDivProject").options[projectList.indexOf(td[3].getAttribute("title"))-1].selected = true;
            document.getElementById("topDivVersion").value = td[4].getAttribute("title");
            document.getElementById("topDivDomain").value = td[7].getAttribute("title");
            document.getElementById("topDivPath").value = td[1].getAttribute("title");
            document.getElementById("topDivDescribe").value = td[6].getAttribute("title");
            document.getElementById("topDivHeader").value = td[8].getAttribute("title");
            document.getElementById("topDivParameter").value = topDivParameter;
            document.getElementById("topDivResponse").value = td[5].getAttribute("title");
        }else{
            document.getElementById("apiId").innerText = "";
            document.getElementById("topDivVersion").value = "";
            document.getElementById("topDivDomain").value = "";
            document.getElementById("topDivPath").value = "";
            document.getElementById("topDivDescribe").value = "";
            document.getElementById("topDivHeader").value = "";
            document.getElementById("topDivParameter").value = "";
            document.getElementById("topDivResponse").value = '{"responseHeader":{},"responseBody":{}}';
        }

        //显示页面
        topDiv.style.marginTop = document.documentElement.scrollTop + "px";
        topDiv.style.display = "block";
    }
    if (mySwitch == "close") topDiv.style.display = "none";
}



//“保存”按钮方法
function saveApi(){
    var apiId = document.getElementById("apiId").innerText;

    var path = document.getElementById("topDivPath").value;
    var domain = document.getElementById("topDivDomain").value;
    if (path.indexOf("/") != 0)
        path = "/" + path;
    if (domain.indexOf("http://") != 0 && domain.indexOf("https://") != 0)
        domain = "http://" + domain;
    var saveDate = {
        "method": selectedText(document.getElementById("topDivMethod")),
        "domain": domain,
        "header": document.getElementById("topDivHeader").value.replace(/\s/g,""),
        "path": path,
        "parameter": document.getElementById("topDivParameter").value.replace(/\s/g,""),
        "response": document.getElementById("topDivResponse").value.replace(/\s/g,""),
        "describe_api": document.getElementById("topDivDescribe").value,
        "project": document.getElementById("topDivProject").selectedIndex + 1,
        "version": document.getElementById("topDivVersion").value
    };

    var xmlhttp = new XMLHttpRequest();
    if (apiId != ""){
        //编辑接口
        saveDate["id"] = apiId;
        xmlhttp.open("POST", "/apiTest/updateApi", true);
        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState==4){
                if (xmlhttp.status==200){
                    var r = JSON.parse(xmlhttp.response);
                    if (r["apistatus"] == "1"){
                        controlTopDiv("close", "", "");
                        queryApi(); //刷新列表
                    }else{
                        alert(r["errorMsg"]);
                    }

                }else{
                    alert("服务器异常");
                }
            }
        };
    }else{
        //新增api的接口
        xmlhttp.open("POST", "/apiTest/addApi", true);
        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState==4){
                if (xmlhttp.status==200){
                    var r = JSON.parse(xmlhttp.response);
                    if (r["apistatus"] == "1"){
                        controlTopDiv("close", "", "");
                        queryApi(); //刷新列表
                    }else{
                        alert(r["errorMsg"]);
                    }

                }else{
                    alert("服务器异常");
                }
            }
        };
    }

    //添加接口的请求

    xmlhttp.send(JSON.stringify(saveDate));
}

//“查询”按钮方法
function queryApi(){
    var project = document.getElementById("project");
    var projectValue = project[project.selectedIndex].value;

    var method = document.getElementById("method");
    var methodValue = method[method.selectedIndex].text;

    var version = document.getElementById("version");
    var versionValue = version[version.selectedIndex].text;

    var pathValue = document.getElementById("path").value;

    if (projectValue == "0") projectValue = "";
    if (methodValue == "所有请求") methodValue = "";
    if (versionValue == "全部版本") versionValue = "";

    requestGetApiList(projectValue, methodValue, pathValue, versionValue);
}

//加载getApiList接口
function requestGetApiList(project, method, path, version){
    var xmlhttp1 = new XMLHttpRequest();
    xmlhttp1.onreadystatechange = function(){
        if (xmlhttp1.readyState==4 && xmlhttp1.status==200){
            var apiList = JSON.parse(xmlhttp1.response);
            loadApiList(apiList["result"]);
        }
    };
    var url = "/apiTest/getApiList?project=" + project + "&method=" + method + "&path=" + path + "&version=" + version;
    xmlhttp1.open("GET", url, true);
    xmlhttp1.send();
}

//点击“健康检查”触发的操作
function checkHealth(){
    var trList = document.getElementById('infoTable').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    //从下标1开始
    oneCheckHealth(1, trList, trList.length);

}

function oneCheckHealth(fromIndex, trList, endIndex){
    //isHealth字段的绑定方法，点击字段值将会做接口请求，返回具体的颜色来表示返回状态
    //red:#FF0000 blue:#0000FF black:#000000 yellow:FFFF00 green:#00FF00
    var isHealthColor = {"red":"#FF0000","blue":"#0000FF","black":"#000000","yellow":"#FFFF00","green":"#00FF00"};
    var isHealthColorInfo = {"red":"返回4xx 或5xx","blue":"请求超时5秒","black":"找不到地址","yellow":"json状态码不符合预期","green":"正常"};
    var td;
    if (fromIndex == undefined && endIndex == undefined){
        //这里的trlist只有单个tr
        td = trList.getElementsByTagName("td");
    }else{
        if (fromIndex == endIndex){
            return;
        }
        td = trList[fromIndex].getElementsByTagName("td");
    }
    var x8 = td[8].getAttribute("title");

    //loading
    td[9].innerText = "Loading...";
    td[9].style.backgroundColor = "#ffffff";

    var saveDate = {"method":td[0].getAttribute("title"),
        "path":td[1].getAttribute("title"),
        "parameter":td[2].getAttribute("title"),
        "header":td[8].getAttribute("title"),
        "domain":td[7].getAttribute("title"),
        "expectResponse":td[5].getAttribute("title")
    };

    //请求apiTest/checkApiHealth接口
    //新增api的接口
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("POST", "/apiTest/checkApiHealth", true);
    xmlHttp.onreadystatechange = function(){
        if (xmlHttp.readyState==4){
            if (xmlHttp.status==200){
                var r = JSON.parse(xmlHttp.response);
                if (r["apistatus"] == "1"){
                    td[9].style.backgroundColor = isHealthColor[r["result"]];
                    td[9].setAttribute("title", isHealthColorInfo[r["result"]]);
                    td[9].innerText = "";
                    if (fromIndex != undefined){
                        oneCheckHealth(fromIndex+1, trList, trList.length);
                    }
                }else{
                    alert(r["errorMsg"]);
                }
            }else{
                //alert("服务器异常");
            }
        }
    };
    xmlHttp.send(JSON.stringify(saveDate));
}



//通过返回数据创建api的列表
function loadApiList(jsonData){
    var infoTable = document.getElementById("infoTable").getElementsByTagName("tbody")[0];

    //清空所有行,保留抬头
    var firstTr = infoTable.getElementsByTagName("tr")[0];
    infoTable.innerText = "";
    infoTable.appendChild(firstTr);

    for (var i = 0; i < jsonData["datas"].length; i++){
        var oneApi = jsonData["datas"][i]["data"];

        var id = oneApi[0];
        var idTr = document.createElement("tr");
        idTr.setAttribute("id", id);
        //idTr.setAttribute("onclick", "controlTopDiv('open', '编辑接口', this)");

        var method = oneApi[1];
        var methodTd = document.createElement("td");
        methodTd.setAttribute("title", method);
        methodTd.innerText = method;
        idTr.appendChild(methodTd);

        var path = oneApi[4];
        var pathTd = document.createElement("td");
        pathTd.setAttribute("title", path);
        pathTd.innerText = path;
        idTr.appendChild(pathTd);

        var parameter = oneApi[5];
        var parameterShort;
        if (parameter.length > 20){
            parameterShort = oneApi[5].substr(0, 20) + "...";
        }else{
            parameterShort = parameter;
        }
        var parameterTd = document.createElement("td");
        parameterTd.setAttribute("title", parameter);
        parameterTd.innerText = parameterShort;
        idTr.appendChild(parameterTd);

        var project = projectList[oneApi[8]];
        var projectTd = document.createElement("td");
        projectTd.setAttribute("title", project);
        projectTd.innerText = project;
        idTr.appendChild(projectTd);

        var version = oneApi[9];
        var versionTd = document.createElement("td");
        versionTd.setAttribute("title", version);
        versionTd.innerText = version;
        idTr.appendChild(versionTd);

        var expectResponse = oneApi[6];
        var expectResponseShort;
        if (expectResponse != null && expectResponse.length > 35){
            expectResponseShort = oneApi[6].substr(0, 35) + "...";
        }else{
            expectResponseShort = expectResponse;
        }
        var expectResponseTd = document.createElement("td");
        expectResponseTd.setAttribute("title", expectResponse);
        expectResponseTd.innerText = expectResponseShort;
        idTr.appendChild(expectResponseTd);

        var describe = oneApi[7];
        var describeTd = document.createElement("td");
        describeTd.setAttribute("title", describe);
        describeTd.innerText = describe;
        idTr.appendChild(describeTd);

        //隐藏参数 编辑的时候才提供数据
        var domain = oneApi[2];
        var domainTd = document.createElement("td");
        domainTd.setAttribute("title", domain);
        domainTd.setAttribute("style", "display:none");
        idTr.appendChild(domainTd);

        //隐藏参数 编辑的时候才提供数据
        var response = oneApi[3];
        if (response == null) response = "";
        var responseTd = document.createElement("td");
        responseTd.setAttribute("title", response);
        responseTd.setAttribute("style", "display:none");
        idTr.appendChild(responseTd);

        var isHealthTd = document.createElement("td");
        isHealthTd.setAttribute("title", "");
        idTr.appendChild(isHealthTd);

        infoTable.appendChild(idTr);
    }

    //给每个td绑定点击事件，实现编辑操作
    var bandTD = [0, 1, 2, 3, 4, 5, 6];     //td中需要绑定的数据
    var trList = document.getElementById("infoTable").getElementsByTagName("tbody")[0].getElementsByTagName("tr");
    for (var trListIndex = 1; trListIndex < trList.length; trListIndex++){
        var tdList = trList[trListIndex].getElementsByTagName("td");
        for (var bandTDIndex in bandTD){
            tdList[bandTD[bandTDIndex]].onclick = function(){controlTopDiv('open', '编辑接口', this.parentNode);};
        }
        //绑定isHealth点击事件
        tdList[9].onclick = function(){oneCheckHealth(undefined, this.parentNode, undefined)};
    }
}

